package com.xiong.excel.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.xiong.excel.constant.SystemConstants;
import com.xiong.excel.pojo.PurchaseContract;
import com.xiong.excel.pojo.PurchaseContractNew;
import com.xiong.excel.utils.BigDecimalCount;
import com.xiong.excel.utils.ConvertUpMoney;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author XiongDa
 */
@Slf4j
public class PurchaseContractNewListener extends AnalysisEventListener<PurchaseContractNew> {

    // 记录总导出的文件数量
    int i = 0;

    // 记录一共解析了多少条记录
    int j = 0;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 50;

    private List<PurchaseContractNew> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invoke(PurchaseContractNew data, AnalysisContext context) {

        log.info("解析到第：{} 条数据:{}", ++j, JSON.toJSONString(data));

        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData(cachedDataList);
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    /**
     * 加上存储数据库
     */
    private void saveData(List<PurchaseContractNew> cachedDataList ) {

        log.info("{} 条数据，开始导出！", cachedDataList.size());

        for (PurchaseContractNew purchaseContract : cachedDataList) {

            log.info("{} 第:{} 条数据,开始导出===========================================", purchaseContract.getName(), ++i);

            //大写金额转换  实际金额  3,123 => 叁千壹佰贰十叁元
            String actualAmount = purchaseContract.getActualAmount().replace(",", "");
            purchaseContract.setActualAmount(actualAmount);
            purchaseContract.setActualAmountUp(ConvertUpMoney.toChinese(actualAmount));

            //导出目录 和文件名配置
            //去除 / 符合导致bug   文件名字包含 / 会导致创建下一级目录, 所以把 / 替换成 - 符号
            String fileName = (purchaseContract.getSupplier() + purchaseContract.getContractId() + purchaseContract.getProject() + ".xls").replace("/", "-");
            String targetFileName = SystemConstants.TARGET_FILE_NAME + fileName;

            System.out.println("--------------------------------------------------------------------");
            System.out.println(purchaseContract);
            System.out.println("---------------------------------------------------------------------");
            // 这里 会填充到第一个sheet， 然后文件流会自动关闭
            EasyExcel.write(targetFileName)
                    .withTemplate(SystemConstants.TEMPLATE_FILE_NAME)
                    .sheet()
                    .doFill(purchaseContract);
        }
        log.info("{} 条数据，导出完成！=============================================================", cachedDataList.size());
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
        // 如果想转成成 Map<Integer,String>
        // 方案1： 不要implements ReadListener 而是 extends AnalysisEventListener
        // 方案2： 调用 ConverterUtils.convertToStringMap(headMap, context) 自动会转换
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData(cachedDataList);
        log.info("=====================所有数据解析完成！===================================");
        log.info("共解析到: {} 条数据", j);
        log.info("共导出: {} 个文件", i);
    }


}